<template>
  <el-dialog :title=title
             v-if="open"
             :visible.sync="open"
             :modal=true
             width="80%"
             center
  >
    <div class="app-container">
      <div style="font-size: 20px;">订单信息</div>
      <!--横线组件纯纯为了页面好看-->
      <el-divider></el-divider>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单编号" prop="orderCode">
              <el-input v-model="form.orderCode" placeholder="请输入订单编号" :readonly="!(optType==='add')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="到货日期" prop="materialDeadline">
              <el-date-picker
                v-model="form.materialDeadline"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择到货日期" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="vendorName">
              <el-input v-model="form.vendorName" readonly="readonly" placeholder="请选择供应商">
                <el-button slot="append" @click="handleSelectVendor" icon="el-icon-search"></el-button>
              </el-input>
              <VendorSelect ref="vendorSelect" @onSelected="onVendorSelected"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商联系人" prop="contact">
              <el-input v-model="form.contact" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商联系人电话" prop="contactTel">
              <el-input v-model="form.contactTel" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购人员" prop="buyer">
              <el-input v-model="form.buyer" placeholder="请选择采购人员" readonly>
                <el-button
                  slot="append"
                  @click="handleSelectUser"
                  icon="el-icon-search">
                </el-button>
              </el-input>
              <UserSelect ref="userSelect" @onSelected="onUserSelected"></UserSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购部门" prop="buyerDept">
              <el-input v-model="form.buyerDept" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!--横线组件纯纯为了页面好看-->
      <el-divider></el-divider>
      <el-row style="margin-bottom: 20px;">
        <el-col :span="1.5">
          <div style="font-size: 20px; margin-top: 5px">采购物料</div>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="handleAdd" style="margin-left: 20px;">点击添加物料</el-button>
        </el-col>
        <el-col :span="2">
          <el-upload
            action="#"
            ref="upload"
            class="upload-demo"
            accept=".xlsx,.xls"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleUpload">
            <template >
              <el-button type="primary">导入数据</el-button>
            </template>
          </el-upload>

        </el-col>
      </el-row>
      <el-table border :data="addGoodsList" show-summary :summary-method="getSummaries" max-height="600">
        <el-table-column label="采购计划号" align="center" prop="planNumber"/>
        <el-table-column label="物料编号" align="center" prop="itemCode"/>
        <el-table-column label="物料名称" align="center" prop="itemName"/>
        <el-table-column label="规格型号" align="center" prop="specification"/>
        <el-table-column label="单位" align="center" prop="unitOfMeasure"/>
        <el-table-column label="分类" align="center" prop="itemTypeName"/>
        <el-table-column
          v-for="col in columnsConfig"
          :key="col.prop"
          :label="col.label"
          :prop="col.prop"
          :width="col.width"
          :align="col.align"
          v-if="col.show">
        </el-table-column>
        <el-table-column label="客户" align="center" prop="clientName" />
        <el-table-column label="备注" align="center" prop="remark" width="150" >
          <div class="item" slot-scope="scope">
            <el-input class="item__input" v-model="scope.row.remark" placeholder="请输入备注" size="mini"
                      style="width:130px"></el-input>
          </div>
        </el-table-column>
        <el-table-column label="采购单价" align="center" prop="estimatedUnitPrice" width="200" >
          <div class="item" slot-scope="scope">
            <el-input-number class="item__input" v-model="scope.row.estimatedUnitPrice" placeholder="请输入价格"
                             size="mini" style="width:150px"
                             :min="0"
                             :max="1000000"
                             :precision="7"
                             controls-position="right"
                             @change="handleEdit(scope.$index, scope.row)"></el-input-number>
          </div>
        </el-table-column>
        <el-table-column label="采购数量" align="center" prop="quantity" width="150" >
          <div class="item" slot-scope="scope">
            <el-input-number v-model="scope.row.quantity" controls-position="right" :min="1"
                              size="mini" style="width:130px"
                             @input="handleEdit(scope.$index, scope.row)"
                             @change="handleChangeQuantity(scope.$index, scope.row)"/>
          </div>
        </el-table-column>
        <el-table-column label="采购总价" align="center" prop="total" width="150" >
          <div class="item" slot-scope="scope">
            <el-input class="item__input" v-model="scope.row.total" placeholder="采购总价" size="mini"
                      style="width:100px" @change="handleChangeTotal(scope.$index, scope.row)"></el-input>
          </div>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="deleteGoodsList(scope.row)"
            >删除商品
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
        <el-button type="primary" @click="submitForm">保存采购订单</el-button>
        <el-button type="primary" @click="cancel">返 回</el-button>
      </div>

      <!--选择商品信息弹出框-->
      <ItemSelect ref="itemSelect" @onSelected="onItemSelected" :purchasedQuantity="purchasedQuantity"></ItemSelect>
    </div>
  </el-dialog>
</template>

<script>
import {addOrder, updateOrder, getOrder,character} from "@/api/mes/cg/order";
import {genCode} from "@/api/system/autocode/rule"
import ItemSelect from "@/views/mes/cg/order/itemSelect.vue";
import VendorSelect from "@/components/vendorSelect/single.vue";
import PlanSelect from "@/views/mes/cg/order/planSelect.vue";
import UserSelect from "@/components/userSelect/single.vue";
import {getColumnsConfigKey} from "@/api/system/columnsconfig";
import * as xlsx from 'xlsx'
import {getUserProfile} from "@/api/system/user";
export default {
  name: "addOrder",
  components: {ItemSelect, VendorSelect, PlanSelect, UserSelect},
  dicts: ['erp_payment_type'],
  data() {
    return {
      purchasedQuantity: {},
      optType: undefined,
      open: false,
      title: null,
      // 遮罩层
      loading: true,
      // 添加的商品信息表格数据
      addGoodsList: [],
      // 供应商列表
      vendorList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderCode: [
          {required: true, message: "订单编号不能为空", trigger: "blur"}
        ],
        vendorName: [
          {required: true, message: "供应商不能为空", trigger: "blur"}
        ],
        materialDeadline: [
          {required: true, message: "到货日期不能为空", trigger: "change"}
        ],
        buyer: [
          {required: true, message: "采购人员不能为空", trigger: "blur"}
        ]

      },
      columnsConfig:[],
      user: {},
    };
  },
  created() {
    /* this.getList();
     //查询商品表方法
     this.getGoodsList();
     //查询供应商列表方法
     this.getSupplierlist();*/
    this.getItemBase();
    this.getUser();
  },
  methods: {
    init() {
      this.purchasedQuantity = {};
      this.form = {
        id: null,
        orderCode: null,
        materialDeadline: new Date().toISOString().split('T')[0],
        vendorId: null,
        vendorName: null,
        vendorCode: null,
        contact: null,
        contactTel: null,
        paymentType: null,
        estimatedCost: null,
        remarks: null,
        status: 3,
        userId: this.user.userId,
        buyer: this.user.nickName,
        deptId: this.user.dept.deptId,
        buyerDept: this.user.dept.deptName
      };
      this.resetForm("form");
      this.handleAutoGenChange();
    },
    getItemBase(){
      getColumnsConfigKey('MdItem_Base').then(res=>{
        this.columnsConfig = JSON.parse(res.data);
      })
    },
    update(id) {
      this.init();
      getOrder(id).then(response => {
        this.form = response.data;
        this.addGoodsList = response.data.cgPurchaseOrderDetailsList;
        this.addGoodsList.forEach(row => {
          this.purchasedQuantity[row.planDetailId] = row.quantity;
        })
      });
    },
    //删除添加的商品方法
    deleteGoodsList(row) {
      this.addGoodsList.splice(this.addGoodsList.indexOf(row), 1);
    },

    //商品小计
    getSummaries(param) {
      const {columns, data} = param;
      const sums = []; //声明变量
      let indexNum = 0;
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "小计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (column.property === "total") {
          indexNum = index;
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          this.form.estimatedCost = sums[indexNum];
          sums[index]+=' 元'
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },

    //商品总价计算
    handleEdit(index, row) {
      if (row.quantity && row.estimatedUnitPrice) {
        row.total = parseFloat(Number(row.quantity) * Number(row.estimatedUnitPrice)).toFixed(2)
      }
    },
    //反算商品单价
    handleChangeTotal(index, row){
      if (row.quantity && row.total) {
        row.estimatedUnitPrice = parseFloat(Number(row.total) / Number(row.quantity)).toFixed(7)
      }
    },
    handleChangeQuantity(index, row) {
      if (row.quantity > (row.planQuantity - row.purchasedQuantity)) {
        this.$modal.msgError("采购数量大于计划采购数量");
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    /** 新增采购商品按钮操作 */
    handleAdd() {
      this.$refs.itemSelect.showFlag = true;
      this.$refs.itemSelect.getList();
      this.$refs.itemSelect.selectedRows1 = this.addGoodsList;
    },
    /** 新增提交按钮 */
    submitForm() {
      let that = this;
      this.$modal.confirm('是否确认保存采购订单？').then(function () {
        that.$refs["form"].validate(valid => {
          if (valid) {
            //判断是否添加商品
            if (that.addGoodsList.length === 0) {
              that.$modal.msgError("请添加商品");
              return;
            }
            if (that.addGoodsList.length !== 0) {
              for (let i = 0; i < that.addGoodsList.length; i++) {
                if (that.addGoodsList[i].estimatedUnitPrice === null || that.addGoodsList[i].estimatedUnitPrice <= 0) {
                  that.$modal.msgError("请填写采购单价");
                  return;
                }
                if (that.addGoodsList[i].quantity === null || that.addGoodsList[i].quantity === undefined) {
                  that.$modal.msgError("请填写采购数量");
                  return;
                }
                if (that.addGoodsList[i].quantity <= 0) {
                  that.$modal.msgError("请填写正确的采购数量");
                  return;
                }
              }
            }
            that.form.cgPurchaseOrderDetailsList = that.addGoodsList;
            if (that.form.id) {
              updateOrder(that.form).then(response => {
                that.$modal.msgSuccess("修改成功");
                that.open = false;
                that.$parent.getList();
                that.cancel();
              })
            } else {
              //调取新增接口
              addOrder(that.form).then(response => {
                that.$modal.msgSuccess("新增成功");
                that.open = false;
                that.$parent.getList();
                that.cancel();
              });
            }
          }
        })


      });
    },
    //自动生成编码
    handleAutoGenChange() {
        genCode('PURCHASE_ORDER_CODE').then(response => {
          this.form.orderCode = response;
        });
    },
    //物料选择弹出框
    onItemSelected(obj) {
      if (this.addGoodsList && this.addGoodsList.length > 0) {
        this.addGoodsList.forEach((row, index) => {
          obj.find((item1) => {
            if (item1.planDetailId == row.planDetailId) {
              item1.estimatedUnitPrice = row.estimatedUnitPrice;
              item1.quantity = row.quantity;
              item1.total = row.total;
              item1.remark = row.remark;
            }
          })
        })
      }
      this.addGoodsList = obj;
      /*
        let one=this.addGoodsList.find(item=>item.itemCode===obj.itemCode);
        if(one){
          this.$modal.msgError("该物料已添加");
          return;
        }
        let data={
          itemId:obj.itemId,
          itemCode:obj.itemCode,
          itemName:obj.itemName,
          itemType:obj.itemType,
          itemTypeName:obj.itemTypeName,
          specification:obj.specification,
          unitOfMeasure:obj.unitOfMeasure,
          estimatedUnitPrice:obj.referencePrice,
          quantity:0,
          total:0
        }
        this.addGoodsList.push(data);*/
    },
    //供应商选择
    handleSelectVendor() {
      this.$refs.vendorSelect.showFlag = true;
    },
    //供应商选择弹出框
    onVendorSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.vendorId = obj.vendorId;
        this.form.vendorCode = obj.vendorCode;
        this.form.vendorName = obj.vendorName;
        if (obj.contact1 != null && obj.contact1Tel != null) {
          this.form.contact = obj.contact1;
          this.form.contactTel = obj.contact1Tel;
        } else {
          this.form.contact = obj.contact2;
          this.form.contactTel = obj.contact2Tel;
        }
      }
    },
    handleSelectPlan() {
      this.$refs.PlanSelect.showFlag = true;
      this.$refs.PlanSelect.selectedPlanId = undefined;
    },
    onPlanSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.planId = obj.planId;
        this.form.planNumber = obj.planNumber;
        this.form.planName = obj.planName;
        this.form.planDate = obj.planDate;
        this.form.materialDeadline = obj.materialDeadline;
      }
    },
    handleSelectUser() {
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.userId = obj.userId;
        this.form.buyer = obj.nickName;
        this.form.deptId = obj.dept.deptId;
        this.form.buyerDept = obj.dept.deptName;
      }
    },
    handleUpload(event){
      const file = event.raw;
      const reader=new FileReader();
      reader.onload=(e)=>{
        const data= new Uint8Array(e.target.result);
        const workbook= xlsx.read(data,{type:'array'});
        const worksheet=workbook.Sheets[workbook.SheetNames[0]];
        const jsonData=xlsx.utils.sheet_to_json(worksheet,{header:1});
        //表头数据
        let headers=jsonData[0];
        jsonData.splice(1).forEach(row=>{
          const rowData=row.reduce((accumulator,item,index)=> {
            let key=headers[index];
            let v=character[key];
            if(v){
              let column=v.column;
              let type=v.type;
              if(type==='number' && item){
                accumulator[column]=Number(item);
              }else{
                accumulator[column]=item;
              }
            }
            return accumulator;

          },{})
          this.addGoodsList.push(rowData);
        })
      }
      reader.readAsArrayBuffer(file);
    },
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
  }
};
</script>

<style scoped>

</style>
